package com.example.demo.init;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.PmWorkCard;
import com.example.demo.mapper.PmWorkCardMapper;
import com.example.demo.model.EsPmWorkCard;
import com.example.demo.repository.PmWorkCardRepository;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

//@Component
@Slf4j
public class InitData {

    @Autowired
    private PmWorkCardRepository pmWorkCardRepository;

    @Autowired
    private PmWorkCardMapper pmWorkCardMapper;

    @PostConstruct
    public void init() {
        long count = pmWorkCardRepository.count();
        Long mysqlCount = pmWorkCardMapper.selectCount(null);

        if (Objects.equals(count, mysqlCount)) {
            log.info("无须初始化数据");
            return;
        }

        int currentPage = 497;
        int pageSize = 5000;

        while (true) {
            Page<PmWorkCard> pmWorkCardPage = pmWorkCardMapper.selectPage(Page.of(currentPage, pageSize), null);

            List<PmWorkCard> records = pmWorkCardPage.getRecords();

            if (records.isEmpty()) {
                log.info("同步数据完成");
                break;
            }

            log.info("当前处理 {} 页", currentPage);


            List<EsPmWorkCard> esDataList = records.stream().map(item -> {
                EsPmWorkCard es = new EsPmWorkCard();
                BeanUtils.copyProperties(item, es);
                return es;
            }).collect(Collectors.toList());

            pmWorkCardRepository.saveAll(esDataList);

            log.info("处理 {} 页完成", currentPage);

            currentPage++;


        }


    }
}
